<template>
  <div class="quality-inspection-page">
    <div class="breadcrumb">
      <Breadcrumb :data="breadcrumbData"></Breadcrumb>
    </div>
    <main>
      <div class="tree-container">
        <div class="search-content">
          <el-input
            placeholder="请输入"
            v-model.trim="filterText"
            suffix-icon="el-icon-search"
            @input="handleInput">
          </el-input>
          <div class="btns">
            <span class="icon">
              <i :class="['el-icon-arrow-up', expandAll ? 'open' : 'close']" @click="toggle"></i>
            </span>
            <span class="icon">
              <i v-if="hasTreeAdd" class="el-icon-plus" @click="addArea"></i>
            </span>
          </div>
        </div>
        <el-tree
          :data="treeData"
          :default-expand-all="expandAll"
          :current-node-key="selectKey"
          :indent="10"
          node-key="id"
          ref="tree"
          :highlight-current="true"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :filter-node-method="filterNode">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="label" :title="node.label">{{ node.label }}</span>
            <span class="btns">
              <i v-if="hasTreeEdit" class="el-icon-edit-outline" @click="editArea(data)"></i>
              <i v-if="hasTreeDel" class="el-icon-delete" @click="delArea(data)"></i>
            </span>
          </span>
        </el-tree>
      </div>
      <div class="table-container">
        <div class="search-container">
          <div class="search-content">
            <el-input
              class="search-input"
              placeholder="请输入需要搜索的内容"
              v-model="condition"
              suffix-icon="el-icon-search"
              @blur="handleSearch"
              @keydown.native.enter="handleSearch">
            </el-input>
          </div>
        </div>
        <div class="table-main">
          <div class="btn-container">
            <!--          <h4 class="title">质量巡检列表</h4>-->
            <div class="btns">
              <el-button
                v-if="hasTabSet"
                size="small"
                type="primary"
                @click="addPerson">设置责任人</el-button>
              <el-button
                v-if="hasTabAdd"
                size="small"
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd">新增</el-button>
            </div>
          </div>
          <el-tabs v-model="status" @tab-click="handleClick">
            <el-tab-pane label="未初审" name="0"></el-tab-pane>
            <el-tab-pane label="未整改" name="1"></el-tab-pane>
            <el-tab-pane label="未复核" name="2"></el-tab-pane>
            <el-tab-pane label="已完成" name="3"></el-tab-pane>
            <el-tab-pane label="初审失败" name="4"></el-tab-pane>
          </el-tabs>
        </div>
        <el-table
          class="table-content"
          v-loading="tableLoading"
          element-loading-custom-class="custom-load"
          :data="tableData"
          row-key="id">
          <el-table-column label="序号" type="index" width="80"></el-table-column>
          <el-table-column prop="areaName" label="检查区域" width="300" show-overflow-tooltip></el-table-column>
          <el-table-column prop="severityLevel" label="严重程度">
            <template slot-scope="scope">
              <span>{{ severityLevelObj[scope.row.severityLevel] || ''}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createrUserName" label="发起人"></el-table-column>
          <el-table-column prop="rectifyUserName" label="整改人"></el-table-column>
          <el-table-column prop="inspectDate" label="检查日期"></el-table-column>
          <el-table-column prop="rectifyDate" label="整改日期"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <span :class="['status', `status_${scope.row.status}`]">
                {{ statusObj[scope.row.status] || '' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template v-if="scope.row.status !== '4'" slot-scope="scope">
              <span style="display: none"></span>
              <span
                v-if="hasTableCheck && scope.row.hasCheck"
                class="prim-btn"
                @click="handleCheck(scope.row)">执行</span>
              <span
                v-if="hasTableSet && scope.row.hasRef"
                class="prim-btn"
                @click="handleCheck(scope.row)">整改</span>
              <span
                v-if="hasTableDetail"
                class="prim-btn"
                @click="setDetail(scope.row)">
                查看
              </span>
              <span
                v-if="hasTableDel"
                class="dar-btn"
                @click="hanldeDelete(scope.row)">删除</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="total > 10"
          :page-size="pageSize"
          :current-page="pageNo"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>
    <add-area
      :type="areaType"
      :options="currentAreaData"
      :visible="areaVisible"
      :menus="treeData"
      :loading="areaLoading"
      @cancel="areaVisible = false"
      @submit="handleSaveArea">
    </add-area>
    <add-inspection
      :type="type"
      title="安全巡检"
      mode="2"
      :options="currentData"
      :visible="visible"
      :menus="treeData"
      :loading="loading"
      @cancel="handleCancel"
      @submit="handleSave">
    </add-inspection>
    <set-responsible-person
      :visible="personVisible"
      :roles="currentRoles"
      :loading="loading"
      @cancel="personVisible = false"
      @submit="handleSavePerson">
    </set-responsible-person>
    <add-inspection-detail
      title="安全巡检"
      :visible="checkVisible"
      :type="type"
      :levels="severityLevelObj"
      :loading="loading"
      :id="checkId"
      @cancel="checkVisible = false"
      @submit="handleSaveCheck">
    </add-inspection-detail>
  </div>
</template>

<script>
import Breadcrumb from '@/components/public/Breadcrumb';
import addArea from '@/components/project/quality/addArea';
import addInspection from '@/components/project/quality/addInspection';
import addInspectionDetail from '@/components/project/quality/addInspectionDetail';
import SetResponsiblePerson from '@/components/project/quality/SetResponsiblePerson';

// 安全检查-隐患排查及治理
export default {
  components: {
    addArea,
    Breadcrumb,
    addInspection,
    addInspectionDetail,
    SetResponsiblePerson
  },
  data() {
    return {
      breadcrumbData: [
        {
          name: '安全管理',
        },
        {
          name: '安全巡检'
        }
      ],
      expandAll: true,
      // 内容搜索项
      condition: '',
      status: '0',
      filterText: '',
      treeData: [],
      currentRoles: null,
      selectKey: '',
      defaultProps: {
        children: 'children',
        label: 'areaName'
      },
      tableLoading: false,
      tableData: [],
      total: 0,
      pageSize: 10,
      pageNo: 1,
      statusObj: {
        '0': '未初审',
        '1': '待整改',
        '2': '未复核',
        '3': '已完成',
        '4': '初审失败'
      },
      severityLevelObj: {
        '0': '物体打击',
        '1': '车辆伤害',
        '2': '机械伤害',
        '3': '起重伤害',
        '4': '触电',
        '5': '淹溺',
        '6': '灼烫',
        '7': '火灾',
        '8': '高处坠落',
        '9': '坍塌',
        '10': '冒顶片帮',
        '11': '透水',
        '12': '放炮',
        '13': '爆炸',
        '14': '中毒和窒息',
        '15': '其他',
      },
      loading: false,
      visible: false,
      type: 'add',
      currentData: {},
      // 区域设置
      areaType: 'add',
      areaVisible: false,
      areaLoading: false,
      currentAreaData: {},
      // 责任人
      personVisible: false,
      // 整改、审核
      checkVisible: false,
      checkId: ''
    };
  },
  computed: {
    projectId() {
      return this.$store.state.currentProjectId;
    },
    userId() {
      return this.$store.state.userInfo.uuid;
    }
  },
  created() {
    const { status } = this.$route.query;
    this.status = status || '0';
    this.getQsRoleList();
    this.getQsAreaTree();
    this.getData();
  },
  methods: {
    getData() {
      if (this.status === '3') { // 已完成
        this.clear();
        this.getQsInspectionList();
        return;
      }
      this.getTableData();
    },
    // 获取已完成数据
    async getQsInspectionList() {
      const params = {
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        condition: this.condition || '',
        projectId: this.projectId,
        type: '2', // 1：质量；2：安全
      };
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getQsInspectionList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        this.total = data.total || 0;
        this.tableData = list;
      }
    },
    // 获取个人质安区域数据
    async getTableData() {
      const params = {
        condition: this.condition || '',
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        projectId: this.projectId,
        status: this.status,
        type: '2', // 1：质量；2：安全
      };
      // 0：未初审；1：未整改；2：未复核；3：已复核
      // switch (this.status) {
      //   case '1':
      //     params.createrUser = this.userId;
      //     break;
      //   case '2':
      //     params.createrUser = this.userId;
      //     break;
      //   default: break;
      // }
      this.tableLoading = true;
      const { success, data: {
        data
      }} = await this.$Model.getQsInPersonList(params);
      this.tableLoading = false;
      if (success && data) {
        const list = data.list || [];
        this.total = data.total || 0;
        this.tableData = list.map(item => {
          const { status } = item;
          return {
            hasCheck: ['0', '2'].includes(status),
            hasRef: status === '1',
            ...item
          };
        });
      }
    },
    // 获取初审角色
    async getQsRoleList() {
      const { success, data: {
        data
      }} = await this.$Model.getQsRoleList({
        pageFlag: false,
        type: '2',
        projectId: this.projectId,
      });
      if (success && data) {
        const list = data.list || [];
        this.currentRoles = list[0];
      }
    },
    // 获取质安区域数据
    async getQsAreaTree() {
      const { success, data: {
        data
      }} = await this.$Model.getQsAreaTree({
        pageFlag: false,
        projectId: this.projectId
      });
      if (success) {
        this.treeData = data || [];
      }
    },
    handleSearch() {
      this.clear();
      this.getData();
    },
    handleInput(val) {
      this.$refs.tree && this.$refs.tree.filter(val);
    },
    toggle() {
      this.expandAll = !this.expandAll;
      try {
        this.changeTreeNodeStatus(this.$refs.tree.store.root);
      } catch (e) {}
    },
    // 改变节点的状态
    changeTreeNodeStatus(node) {
      node.expanded = this.expandAll;
      for (let i = 0; i < node.childNodes.length; i++) {
        // 改变节点的自身expanded状态
        node.childNodes[i].expanded = this.expandAll;
        // 遍历子节点
        if (node.childNodes[i].childNodes.length) {
          this.changeTreeNodeStatus(node.childNodes[i]);
        }
      }
    },
    /**
     * 选中当前文件
     * @param data {Object} 当前节点数据
     * @param node 节点
     */
    handleNodeClick(data, node) {
      const { id } = data;
      this.selectKey = id;
      // this.clear();
      // this.getData();
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.areaName.indexOf(value) !== -1;
    },
    // 清除参数
    clear() {
      this.pageNo = 1;
      this.pageSize = 10;
      this.total = 0;
      this.tableLoading = false;
      this.tableData = [];
    },
    /**
     * pageSize 改变时会触发
     * @param pageSize 每页条数
     */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getData();
    },
    handleClick(e) {
      this.status = e.name;
      this.clear();
      this.getData();
    },
    /**
     * currentPage 改变时会触发
     * @param pageNo 当前页
     */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getData();
    },
    // 新增区域
    addArea() {
      this.areaType = 'add';
      this.currentAreaData = {};
      this.areaLoading = false;
      this.areaVisible = true;
    },
    // 编辑区域
    editArea(data) {
      this.areaType = 'edit';
      this.currentAreaData = { ...data };
      this.areaLoading = false;
      this.areaVisible = true;
    },
    // 删除区域
    delArea(data) {
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delQsAreaTree({
          ids: data.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.getQsAreaTree();
        }
      });
    },
    // 保存区域
    async handleSaveArea(data) {
      const params = {
        projectId: this.projectId,
        ...data
      };
      if (!params.parentId) delete params.parentId;
      if (!params.id) delete params.id;
      this.areaLoading = true;
      const { success } = this.areaType === 'add'
        ? await this.$Model.addQsAreaTree(params)
        : await this.$Model.updateQsAreaTree(params);
      this.areaLoading = false;
      if (success) {
        this.$message.success('保存成功');
        this.getQsAreaTree();
        this.areaVisible = false;
      }
    },
    // 设置责任人
    addPerson() {
      this.loading = false;
      this.personVisible = true;
    },
    // 保存责任人
    async handleSavePerson(options) {
      const params = {
        type: '2',
        projectId: this.projectId,
        ...options
      };
      if (this.currentRoles) params.id = this.currentRoles.id;
      this.loading = true;
      const { success } = this.currentRoles
        ? await this.$Model.updateQsRole(params)
        : await this.$Model.addQsRole(params);
      this.loading = false;
      if (success) {
        this.currentRoles = {
          ...params
        };
        this.$message.success('保存成功');
        this.personVisible = false;
      }
    },
    // 新增
    handleAdd() {
      this.type = 'add';
      this.currentData = {};
      this.loading = false;
      this.visible = true;
    },
    setDetail(row) {
      this.type = 'detail';
      this.checkId = row.id;
      this.checkVisible = true;
    },
    // 审核
    handleCheck(row) {
      const { status } = row;
      if (status === '0') { // 初审
        this.type = 'check';
        this.currentData = { ...row };
        this.visible = true;
        return;
      }
      this.type = status === '1'
        ? 'ref'
        : status === '2' ? 'review' : 'detail';
      this.checkId = row.id;
      this.checkVisible = true;
    },
    // 删除
    hanldeDelete(row) {
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { success } = await this.$Model.delQsInspection({
          ids: row.id
        });
        if (success) {
          this.$message.success('删除成功');
          this.tableData.length < 2 && this.clear();
          this.getData();
        }
      });
    },
    handleCancel() {
      this.loading = false;
      this.visible = false;
    },
    // 保存
    async handleSave(data) {
      let params = {
        type: '2', // 1：质量；2：安全
        projectId: this.projectId,
        ...data
      };
      if (!params.id) delete params.id;
      const { id, status, operatUser } = this.currentData;
      if (this.type === 'check') {
        params = {
          qsId: id,
          operatUser: operatUser || this.userId,
          projectId: this.projectId,
          status: data.hasCheck,
          type: status
        };
      }
      this.loading = true;
      const { success } = this.type === 'add'
        ? await this.$Model.addQsInspection(params)
        : await this.$Model.checkQsInspection(params);
      this.loading = false;
      if (success) {
        this.$message.success('保存成功');
        this.getData();
        this.visible = false;
      }
    },
    async handleSaveCheck(data) {
      const { success } = await this.$Model.checkQsInspection(data);
      if (success) {
        this.$message.success('提交成功');
        this.getData();
        this.loading = false;
        this.checkVisible = false;
      }
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/table';

  .quality-inspection-page {
    width: 100%;
    height: 100%;
    background-color: $baseBg;
    color: #fff;
    main {
      width: 100%;
      height: calc(100% - 40px);
      padding: 20px;
      display: flex;
      justify-content: space-between;
      border-radius: 10px;
      .tree-container {
        width: 400px;
        height: 100%;
        padding: 20px;
        border-radius: 20px;
        background-color: $mainBg;
        .search-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          position: relative;
          .btns {
            margin: 0 5px;
            display: flex;
            align-items: center;
            .icon {
              display: inline-block;
              margin-left: 10px;
              width: 35px;
              height: 35px;
              text-align: center;
              line-height: 35px;
              background-color: rgba(160, 164, 179, 0.4);
              border-radius: 5px;
              cursor: pointer;
              i {
                font-size: 20px;
                transition: transform .3s, color .2s;
                &:hover {
                  color: $lightBtnBg;
                }
                &.close {
                  transform: rotateZ(180deg);
                }
              }
            }
          }
        }
        .el-tree {
          background: $mainBg;
          color: #fff;
          /deep/ .el-tree-node__content {
            height: 40px;
            &:hover {
              color: $mainColor;
              background: transparent;
            }
            .custom-tree-node {
              width: 100%;
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding-right: 5px;
              &:hover {
                .btns {
                  visibility: visible;
                  opacity: 1;
                }
              }
              .label {
                flex: 1;
                width: calc(100% - 100px);
                display: inline-block;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              .btns {
                visibility: hidden;
                opacity: 0;
                transition: all .2s;
                i {
                  font-size: 18px;
                  cursor: pointer;
                }
              }
            }
          }
        }
        .el-tree {
          /deep/ .el-tree-node.is-current > .el-tree-node__content {
            color: $mainColor;
            background: $baseBg;
            .custom-tree-node {
              .btns {
                visibility: visible;
                opacity: 1;
              }
            }
          }
          /deep/ .el-tree-node.is-focusable:not(.is-current) > .el-tree-node__content {
            background: transparent;
          }
        }
      }
      .table-container {
        width: calc(100% - 420px);
        height: 100%;
        background-color: $mainBg;
        padding: 10px 20px;
        border-radius: 20px;
        overflow: hidden;
        .search-container {
          width: 100%;
          height: 80px;
          display: flex;
          justify-content: flex-start;
          align-items: center;
          .search-content {
            width: 600px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .search-input {
              width: 300px;
            }
          }
        }
        .table-main {
          width: 100%;
          height: 80px;
          display: flex;
          align-items: flex-end;
          position: relative;
          > .btn-container {
            position: absolute;
            right: 0;
            top: 0;
            z-index: 1;
            height: 80px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .btns {
              display: flex;
              align-items: center;
            }
          }
          .el-tabs {
            width: 100%;
            /deep/ .el-tabs__active-bar {
              background-color: $mainColor;
            }
          }
          /deep/ .el-tabs__content {
            height: calc(100% - 50px);
            .el-tab-pane {
              height: 100%;
            }
          }
          /deep/ .el-tabs__item {
            color: #fff;
            &.is-active {
              color: $mainColor;
            }
            &:focus.is-active.is-focus:not(:active) {
              box-shadow: 0 0 2px 2px $mainColor inset;
              border-radius: 3px
            }
          }
        }
        .table-content {
          width: 100%;
          height: calc(100% - 200px);
          /deep/ .el-table__body-wrapper {
            height: 100%;
            padding-bottom: 46px;
            overflow-y: auto;
            .status {
              display: inline-block;
              padding: 2px 8px;
              border-radius: 2px;
              &.status_0 {
                border: 1px solid #A1D4FD;
                color: #A1D4FD;
                background-color: rgba(161, 212, 253, .5);
              }
              &.status_1 {
                border: 1px solid #FCD8A1;
                color: #FCD8A1;
                background-color: rgba(252, 216, 161, .5);
              }
              &.status_2 {
                border: 1px solid #A1D4FD;
                color: #A1D4FD;
                background-color: rgba(161, 212, 253, .5);
              }
              &.status_3 {
                border: 1px solid #B4E4BE;
                color: #B4E4BE;
                background-color: rgba(180, 228, 190, .5);
              }
            }
          }
          .img-contianer {
            width: 100px;
            height: 60px;
            position: relative;
            .img-icon {
              position: absolute;
              bottom: -2px;
              right: 0;
              font-size: 24px;
              color: $mainColor;
              span {
                position: absolute;
                top: calc(50% - 8px);
                left: calc(50% - 4px);
                font-weight: bold;
                font-size: 16px;
              }
            }
          }
          /deep/ .img {
            width: 100px;
            height: 60px;
          }
          .iconfont {
            cursor: pointer;
          }
        }
      }
    }
  }
</style>
